package com.gorylenko

import org.gradle.api.Task
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import org.gradle.api.plugins.BasePlugin
import org.gradle.api.plugins.JavaPlugin

class BuildPropertiesPlugin implements Plugin<Project> {
    public static final String TASK_NAME = "generateBuildProperties"

    private static final String CHARSET = "UTF-8"
    private static final String FILENAME = "application.properties"
    private static final String OUTPUT_DIR = "resources/main/config"
    private static final String BUILD_FILENAME = "build-info.properties"
    private static final String BUILD_OUTPUT_DIR = "resources/main/META-INF"

    @Override
    void apply(Project project) {
        def task = project.tasks.create(TASK_NAME, GenerateGitPropertiesTask)
        task.setGroup(BasePlugin.BUILD_GROUP)

        project.plugins.apply JavaPlugin
        project.getTasks().getByName(JavaPlugin.CLASSES_TASK_NAME).dependsOn(task)
    }

    static class GenerateGitPropertiesTask extends DefaultTask {
        @TaskAction
        void generate() {
            generateInfo()
            generateBuildInfo()
        }

        void generateInfo(){
            String epoch = System.env.EPOCH ?: "0"
            String version = System.env.VERSION ?: "DEV"

            def file = getOutputFile(OUTPUT_DIR, FILENAME)
            file.withWriter(CHARSET) { w ->
                w.writeLine "info.version=${epoch}.${version}"
            }
        }

        void generateBuildInfo(){
            def file = getOutputFile(BUILD_OUTPUT_DIR, BUILD_FILENAME)
            file.withWriter(CHARSET) { w ->
                w.writeLine "java=${project.properties.targetCompatibility}"
                w.writeLine "time=${new Date().format("yyyy-MM-dd HH:mm:ss a")}"
                w.writeLine "sprint-boot=${project.properties.springBootVersion}"
            }
        }

        private File getOutputFile(output, filename){
            def dir = new File(project.buildDir, output)
            def file = new File(dir, filename)
            if (!dir.exists()) {
                dir.mkdirs()
            }
            if (file.exists()) {
                assert file.delete()
            }
            assert file.createNewFile()
            return file
        }
    }
}
